<template>
  <a-modal
    :maskClosable="false"
    title="类型名称"
    centered
    :width="850"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @cancel="close"
    @ok="handleSubmit"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="rules"
      layout="horizontal"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
    >
      <a-form-model-item label="类型名称:" prop="ticketName">
        <a-input v-model="form.ticketName" placeholder="请输入类型名称" :maxLength="16" :disabled="disableEditing" />
      </a-form-model-item>

      <a-form-model-item label="报名费用:" prop="price">
        <a-input
          v-if="form.ticketType == TicketTypeEnum.pay"
          style="width:160px"
          v-model="form.price"
          placeholder="请输入报名费用"
          :maxLength="60"
          :disabled="form.ticketType == TicketTypeEnum.free || disableEditing"
          @blur="handlePriceBlur"
        >
          <span slot="addonAfter">元</span>
        </a-input>
        <span v-else>无</span>
        <span class="_ml-10">
          {{ form.ticketType == TicketTypeEnum.free ? '如需收费请添加付费类型' : '付费类型价格不可设置为0；' }}
        </span>
      </a-form-model-item>

      <a-form-model-item label="报名名额:" prop="stockNum">
        <a-input
          v-model="form.stockNum"
          placeholder="不限制"
          :maxLength="60"
          style="width:160px"
          class="_mr-10"
          :disabled="disableEditing"
        />
        <a-popover title="报名名额说明" trigger="hover">
          <template slot="content">
            <p>所有报名类型叠加后的报名名额不可大于活动的“限制报名人数”设定的人数；</p>
            <p>报名名额输入为空设定为不限制报名名额（不会超出限制报名人数）；</p>
            <p>输入为0设定报名名额清空为0；</p>
          </template>
          <a-icon type="question-circle" />
        </a-popover>
      </a-form-model-item>

      <a-form-model-item label="审核设置:" prop="reviewStatus">
        <a-radio-group
          v-model="form.reviewStatus"
          :disabled="disableEditing"
          :options="Dict.getLocalMap('ReviewStatusEnumDict', 'label', 'value')"
        ></a-radio-group>
      </a-form-model-item>

      <a-form-model-item label="报名说明:" prop="introduction">
        <a-textarea
          v-model="form.introduction"
          placeholder="建议填写报名说明、报名规则等"
          :disabled="disableEditing"
          :maxLength="200"
          :rows="4"
        />
      </a-form-model-item>

      <a-form-model-item
        label="报名时间:"
        extra="独立报名时间默认跟活动报名时间一致，如果发生修改，本报名类型报名时间将按设置独立生效"
      >
        <a-radio-group
          v-model="form.buyTimeType"
          :options="Dict.getLocalMap('TicktBuyTimeTypeEnumDict', 'label', 'value')"
          :disabled="disableEditing"
        ></a-radio-group>
        <div class="disFlx" v-if="form.buyTimeType === BuyTimeTypeEnum.custom">
          <a-form-model-item prop="startTime">
            <FlatDateTimePicker
              v-model="form.startTime"
              :minDate="startTimeMinDate"
              :maxDate="startTimeMaxDate"
              :disabled="disableEditing"
              :exceedsUpdDate="true"
            >
            </FlatDateTimePicker>
          </a-form-model-item>
          <span class="_ml-10 _mr-10">-</span>
          <a-form-model-item prop="endTime" extra="结束时间不可小于开始时间">
            <FlatDateTimePicker
              v-model="form.endTime"
              :minDate="endTimeMinDate"
              :maxDate="endTimeMaxDate"
              :disabled="disableEditing"
              :exceedsUpdDate="true"
            >
            </FlatDateTimePicker>
          </a-form-model-item>
        </div>
      </a-form-model-item>

      <a-form-model-item label="报名限制:" prop="buyLimit">
        <div class="disFlxAC min-height-4">
          <a-radio-group
            class="flexS0"
            v-model="form.buyLimit"
            :options="Dict.getLocalMap('BuyLimitEnumDict', 'label', 'value')"
            :disabled="disableEditing"
          ></a-radio-group>
          <div v-if="form.buyLimit === BuyLimitEnum.YES" class="disFlxAC">
            <!-- <span class="flexS0 _mr-8">最少</span>
            <a-form-model-item prop="buyMinNum" style="margin-bottom: 0">
              <a-input class="_mr-10" style="width:120px" v-model="form.buyMinNum" :disabled="disableEditing">
                <span slot="addonAfter">张</span>
              </a-input>
            </a-form-model-item>
            <span>，</span> -->
            <span class="flexS0 _mr-8">每人最多报名</span>
            <a-form-model-item prop="buyMaxNum" style="margin-bottom: 0">
              <a-input class="_mr-10" style="width:120px" v-model="form.buyMaxNum" :disabled="disableEditing">
                <span slot="addonAfter">位</span>
              </a-input>
            </a-form-model-item>
          </div>
        </div>
      </a-form-model-item>

      <a-form-model-item label="报名身份限制:" prop="buyIdentityLimit">
        <a-radio-group
          v-model="form.buyIdentityLimit"
          :disabled="disableEditing"
          :options="Dict.getLocalMap('BuyIdentityLimitEnumDict', 'label', 'value')"
        ></a-radio-group>
        <div v-if="form.buyIdentityLimit === BuyIdentityLimitEnum.YES" class="disFlx">
          <a-checkbox-group v-model="formMemberIdentityConfigList" name="checkboxgroup" :disabled="disableEditing">
            <a-checkbox
              v-for="(item, index) in memberIdentityConfigList"
              :key="index"
              :value="item.memberLevelId"
              style="width:150px;margin-left:0;font-size:12px"
            >
              {{ item.memberLevelName }}
            </a-checkbox>
          </a-checkbox-group>
        </div>
      </a-form-model-item>

      <a-form-model-item v-if="form.ticketType == TicketTypeEnum.pay" label="会员优惠价:" prop="enabledMemberDiscount">
        <a-switch
          v-model="enabledMemberDiscount"
          :disabled="isEmpty(form.price) || is0(form.price) || disableEditing"
        />
        <div v-if="enabledMemberDiscount">
          <div class="disFlxAC width-28 _pl-16" style="background:#E8FFEA">
            <a-icon type="info-circle" theme="filled" style="color:#FF7D00" />
            <span class="_ml-8">仅活动发布方的会员生效</span>
          </div>
          <div class="disFlx flexWrap">
            <div v-for="(item, index) in form.memberDiscountConfigList" :key="index" class="width-13 disFlx flexCol">
              <span class="fz-12">{{ item.memberLevelName }}：</span>
              <a-input
                :class="[item.errMsg ? 'has-error' : '']"
                class="_mr-10 fz-12"
                style="width:120px;"
                :disabled="disableEditing"
                v-model="item.price"
              >
                <span slot="addonAfter" class="fz-12">元</span>
              </a-input>

              <span style="color:red" class="ant-form-explain"> {{ item.errMsg }}</span>
            </div>
          </div>
        </div>
      </a-form-model-item>

      <a-form-model-item label="隐藏设置:" prop="display">
        <a-checkbox v-model="display" :disabled="disableEditing">
          本类型不对外报名，仅在后台可见
        </a-checkbox>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import {
  ReviewStatusEnum,
  StockLimitEnum,
  BuyLimitEnum,
  BuyTimeTypeEnum,
  BuyIdentityLimitEnum,
  EnabledMemberDiscountEnum,
  TicketTypeEnum,
  ActivitySettlementStatusEnum
} from '@/enums/activity'
import FlatDateTimePicker from '@/components/FlatDateTimePicker'
import SSwitch from '@/components/Switch'
import { priceRegexFinal, intRegex, positiveNumber, decimal2, positiveIntegerRegex } from '@/utils/RegExp.js'
import { cloneDeep } from 'lodash'
import { isEmpty, is0 } from '@/utils/is.js'

const initForm = {
  /**活动id */
  activityUnionId: undefined,
  /**票id */
  id: undefined,
  /**票类型 */
  ticketType: undefined,
  /**票名称 */
  ticketName: undefined,
  /**报名说明*/
  introduction: undefined,
  /**价格 */
  price: undefined,
  /**报名名额限制 */
  stockLimit: StockLimitEnum.NO,
  /**可用报名名额 */
  stockNum: undefined,
  /**报名限制 */
  buyLimit: BuyLimitEnum.NO,
  /**最大购买限制 */
  buyMaxNum: undefined,
  /**最小购买限制 */
  buyMinNum: 1,

  /**是否需要审核 */
  reviewStatus: ReviewStatusEnum.NO,
  /**报名时间类型 */
  buyTimeType: BuyTimeTypeEnum.activityEndTime,
  /**开始时间 */
  startTime: undefined,
  /**结束时间 */
  endTime: undefined,
  /**购买身份限制 */
  buyIdentityLimit: BuyIdentityLimitEnum.NO,
  /**是否隐藏 0 隐藏 1不隐藏 */
  display: 1,
  /**是否开启会员优惠 */
  enabledMemberDiscount: EnabledMemberDiscountEnum.NO,
  /**备注 */
  remarks: undefined,
  memberIdentityConfigList: [],
  memberDiscountConfigList: []
}
export default {
  components: {
    FlatDateTimePicker,
    SSwitch
  },
  computed: {
    disabled() {
      return this.activityType === 'other_join' // 协办方
    },
    disableEditing() {
      return (
        [
          ActivitySettlementStatusEnum.PROGRESS,
          ActivitySettlementStatusEnum.SUCCESS,
          ActivitySettlementStatusEnum.PART_SUCCESS
        ].includes(this.settleStatus) || this.disabled
      )
    },
    formMemberIdentityConfigList: {
      get() {
        return this.form.memberIdentityConfigList.map(item => item.memberLevelId)
      },
      set(val) {
        this.form.memberIdentityConfigList = val.map(memberLevelId => {
          return this.memberIdentityConfigList.find(fitem => fitem.memberLevelId == memberLevelId)
        })
      }
    },
    enabledMemberDiscount: {
      get() {
        return this.form.enabledMemberDiscount == EnabledMemberDiscountEnum.YES ? true : false
      },
      set(val) {
        this.form.enabledMemberDiscount = val ? EnabledMemberDiscountEnum.YES : EnabledMemberDiscountEnum.NO
      }
    },
    display: {
      get() {
        return !this.form.display
      },
      set(val) {
        this.form.display = Number(!val)
      }
    },
    endTimeMaxDate() {
      return this.toggleDate(this.activityEndTime)
    },
    endTimeMinDate() {
      return this.toggleDate(this.form.startTime)
    },
    startTimeMaxDate() {
      return this.toggleDate(this.activityEndTime)
    },
    startTimeMinDate() {
      return this.toggleDate(this.activityStartTime)
    }
  },
  watch: {
    'form.stockNum': {
      handler(val) {
        if (is0(val) || !isEmpty(val)) {
          this.form.stockLimit = StockLimitEnum.YES
        } else {
          this.form.stockLimit = StockLimitEnum.NO
        }
      },
      immediate: true
    },

    // 'form.buyMinNum'() {
    //   this.$refs.form.validateField('buyMinNum')
    //   this.$refs.form.validateField('buyMaxNum')
    // },
    'form.buyMaxNum'() {
      // this.$refs.form.validateField('buyMinNum')
      this.$nextTick(() => {
        this.$refs.form.validateField('buyMaxNum')
      })
    },
    'form.memberIdentityConfigList'() {
      this.$nextTick(() => {
        this.$refs.form.validateField('buyIdentityLimit')
      })
    },
    'form.memberDiscountConfigList': {
      handler(val) {
        val.forEach(item => {
          if (item.price === '' || item.price === undefined) {
            item.errMsg = '请填写价格'
          } else if (!positiveNumber.test(item.price)) {
            console.log(item.price)
            item.errMsg = '请填写数字'
          } else if (!decimal2.test(item.price)) {
            item.errMsg = '价格最多两位小数'
          } else if (Number(item.price) > Number(this.form.price)) {
            item.errMsg = '优惠价不可大于售价'
          } else {
            item.errMsg = ''
          }
        })
      },
      deep: true
    }
  },
  data() {
    return {
      settleStatus: undefined,
      activityType: '',
      BuyTimeTypeEnum,
      BuyLimitEnum,
      BuyIdentityLimitEnum,
      EnabledMemberDiscountEnum,
      TicketTypeEnum,
      visible: false,
      confirmLoading: false,
      activityEndTime: '',
      activityStartTime: '',
      stockLimitMax: 0,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      rules: {
        ticketName: [{ required: true, message: '请填写类型名称', trigger: 'blur' }],
        price: [
          { required: true, message: '请填写报名费用', trigger: 'blur' },
          {
            message: '价格必须是大于0的数字，小数部分最多两位',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (
                this.form.ticketType == TicketTypeEnum.free ||
                (this.form.ticketType == TicketTypeEnum.pay && priceRegexFinal.test(value))
              ) {
                callback()
              } else {
                callback(new Error(rule))
              }
            }
          }
        ],
        stockNum: [
          { pattern: intRegex, message: '报名名额只能输入正整数', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) callback()
              if (Number(value) > this.stockLimitMax) {
                callback('报名名额超过了剩余最大报名数')
              }
              callback()
            }
          }
        ],
        buyMaxNum: [
          {
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (isEmpty(value)) callback('请输入最大报名数量')
              if (!intRegex.test(value)) callback('最大报名数量必须是整数')
              if (is0(value)) callback('最大报名数量不能小于1')
              if (!isEmpty(this.form.stockNum) && Number(value) > Number(this.form.stockNum)) {
                callback('限制报名数量不能大于报名名额')
              }

              callback()
            }
          }
        ],
        buyIdentityLimit: [
          {
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (value === BuyIdentityLimitEnum.YES) {
                if (this.form.memberIdentityConfigList && !this.form.memberIdentityConfigList.length) {
                  callback('请勾选报名身份限制')
                }
              }
              callback()
            }
          }
        ]
      },
      form: {
        ...cloneDeep(initForm)
      },
      memberIdentityConfigList: [],
      ticketTypeConfigList: []
    }
  },
  created() {},
  methods: {
    isEmpty,
    is0,
    handleSubmit() {
      this.$refs.form.validate(flag => {
        if (!flag) {
          this.scrollIntoErrorView()
          return
        }

        const isNoDiscount = this.form.enabledMemberDiscount === EnabledMemberDiscountEnum.NO
        const isErrMsg = !this.form.memberDiscountConfigList.some(item => item.errMsg)
        const enabledMemberDiscountFlag = isNoDiscount ? true : isErrMsg
        if (!enabledMemberDiscountFlag) {
          this.scrollIntoErrorView()
          return
        }
        const repeatNum = this.ticketTypeConfigList.reduce((pre, curr) => {
          if (curr.ticketName === this.form.ticketName && curr.webId !== this.form.webId) return pre + 1
          return pre
        }, 0)

        if (repeatNum >= 1) {
          this.$message.error('类型名称已存在！')
          return
        }
        this.$emit('save', cloneDeep(this.form))
        this.close()
      })
    },

    toggleDate(time) {
      return time ? new Date(time) : null
    },

    scrollIntoErrorView() {
      this.$nextTick(() => {
        const targetElement = document.querySelector('.ant-modal-body .has-error')
        if (targetElement) {
          targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      }, 100)
    },

    async open({
      ticketTypeConfigList,
      maxNum,
      enrollRestrict,
      startTime,
      endTime,
      activityType,
      settleStatus,
      record,
      memberIdentityConfigList,
      memberDiscountConfigList
    }) {
      this.ticketTypeConfigList = ticketTypeConfigList
      this.memberIdentityConfigList = memberIdentityConfigList
      // 计算最大可以设置的报名名额
      this.stockLimitMax = ticketTypeConfigList
        .filter(item => record && item.webId != record.webId)
        .reduce(
          (preV, currV) => {
            if (preV <= 0) return 0
            if (currV.stockLimit === StockLimitEnum.YES) {
              return preV - currV.stockNum
            }
            return preV
          },
          enrollRestrict ? maxNum : Number.MAX_SAFE_INTEGER
        )

      this.form = { buyTimeType: BuyTimeTypeEnum.activityEndTime, ...record }

      this.activityType = activityType
      this.settleStatus = settleStatus
      this.activityEndTime = endTime
      this.activityStartTime = startTime
      this.visible = true

      if (!this.form.memberDiscountConfigList.length) {
        this.form.memberDiscountConfigList = memberDiscountConfigList.map(item => {
          return {
            memberLevelId: item.memberLevelId,
            memberLevelName: item.memberLevelName,
            price: this.form.price,
            errMsg: ''
          }
        })
      }
    },

    close() {
      this.visible = false
      this.activityStartTime = ''
      this.activityEndTime = ''
      this.form = cloneDeep(initForm)

      setTimeout(() => {
        this.$refs.form.clearValidate()
      }, 100)
    },

    handlePriceBlur(event) {
      const value = event.target.value

      if (value <= 0 || isNaN(Number(value))) return

      this.form.memberDiscountConfigList.forEach(item => {
        if (Number(item.price) === Number(this.form.price) || Number(item.price) >= Number(value) || !item.price) {
          item.price = value
        }
      })
    }
  }
}
</script>
